package de.koller.oceanFramework.thread.buffer;

import de.koller.oceanFramework.OceanException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class BufferSender extends Thread {
	
	private final Buffer<Object> buffer;

	private ObjectOutputStream out;
	private final Socket socket;
	
	public BufferSender( Socket socket, Buffer<Object> buffer ) {
		this.buffer = buffer;
		this.socket = socket;
		this.setDaemon( true );
	}

	@Override
	public void run() {
		
		while( true ) {
			try {
				sendAll();
			} catch( Exception ex ) {
				throw new OceanException( ex );
			}
		}
	}
	
	private void sendAll() throws Exception {
		Object data = buffer.pop();
		
		if( out == null )
			out = new ObjectOutputStream( socket.getOutputStream() );
		
		out.writeObject( data );
		out.flush();
	}
	
}
